package com.tanhua.dubbo.api;

import com.tanhua.dubbo.api.mongo.RecommendUserApi;
import com.tanhua.model.mongo.RecommendUser;
import com.tanhua.model.mongo.UserLike;
import com.tanhua.model.vo.PageResult;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.aggregation.TypedAggregation;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 交友模块-服务接口实现类
 */
@DubboService
public class RecommendUserApiImpl implements RecommendUserApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 今日佳人（返回一条记录）
     * toUserId=当前登录用户id
     * order by score desc
     */
    @Override
    public RecommendUser queryWithMaxScore(Long userId) {
        Query query = new Query();
        query.addCriteria(Criteria.where("toUserId").is(userId));//当前登录用户id
        //Sort.by(指定排序方式,指定哪个字段排序)
        query.with(Sort.by(Sort.Direction.DESC,"score"));
        return mongoTemplate.findOne(query,RecommendUser.class);
    }

    /**
     * 分页查询推荐用户列表数据
     * @param userId
     * @param page
     * @return
     */
    @Override
    public PageResult<RecommendUser> findPage(Long userId, Long page, Long pageSize) {
        //定义返回PageResult<RecommendUser>
        PageResult<RecommendUser> pageResult = new PageResult<>();
        Query query = new Query();
        query.addCriteria(Criteria.where("toUserId").is(userId));
        //1查询总记录数
        long counts = mongoTemplate.count(query, RecommendUser.class);
        long start = (page-1)*pageSize;
        //2查询当前页面需要展示的数据
        List<RecommendUser> recommendUsers = new ArrayList<>();
        if(counts > start){ //20 > 27
            //构造分页limit 0,3
            query.limit(pageSize.intValue());//每页查询几条
            query.skip(start);//跳过1条数据
            //query.with(PageRequest.of(page,pageSize));
            query.with(Sort.by(Sort.Direction.DESC,"userId"));
            recommendUsers = mongoTemplate.find(query, RecommendUser.class);
        }
        return new PageResult<>(page,pageSize,counts,recommendUsers);
    }

    /**
     * 根据佳人用户id 当前用户id 查询RecommendUser 获取缘分值
     * @param userId
     * @param personId
     * @return
     */
    @Override
    public RecommendUser findByUserId(Long userId, Long personId) {
        Query query = new Query();
        query.addCriteria(Criteria.where("toUserId").is(userId).and("userId").is(personId));
        return mongoTemplate.findOne(query,RecommendUser.class);
    }

    /**
     * 探花推荐列表查询
     */
    @Override
    public List<RecommendUser> findCards(Long userId, int count) {
        //1 根据userId查询user_like获取 likeUserIds（喜欢 和 不喜欢的用户id 都需要排除）
        Query userLikeQuery = new Query();
        userLikeQuery.addCriteria(Criteria.where("userId").is(userId));//当前用户id
        List<UserLike> userLikeList = mongoTemplate.find(userLikeQuery, UserLike.class);
        List<Long> likeUserIds = new ArrayList<>();
        if (!CollectionUtils.isEmpty(userLikeList)){
            likeUserIds = userLikeList.stream().map(UserLike::getLikeUserId).collect(Collectors.toList());//喜欢或不喜欢的用户ids
          }
        //2 随机查询RecommendUser表 以及 排除likeUserIds
        //2.1 构造条件  toUserId=当前用户id  userId排除likeUserIds（userId not in(1,2,3)）
        Criteria criteria = Criteria.where("toUserId").is(userId).and("userId").nin(likeUserIds);
        //2.2 随机取出10条推荐用户
        TypedAggregation<RecommendUser> recommendUserTypedAggregation = TypedAggregation.newAggregation(RecommendUser.class, Aggregation.match(criteria), Aggregation.sample(count));
        AggregationResults<RecommendUser> aggregate = mongoTemplate.aggregate(recommendUserTypedAggregation, RecommendUser.class);
        return aggregate.getMappedResults();
    }


    /**
     * 查询匹配度
     * @param id
     * @param userId
     * @return
     */
    @Override
    public Integer findScore(Long id, Long userId) {

        Query query = new Query(Criteria.where("userId").is(id).and("toUserId").is(userId));
        RecommendUser recommendUser = mongoTemplate.findOne(query, RecommendUser.class);
        Integer score1 =0;
        if (recommendUser != null){
        Double score = recommendUser.getScore();
         score1 = score.intValue();
        }
        return score1;
    }

}
